package com.lzy.chat.f_config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.lzy.chat.a_entity.User;
import com.lzy.chat.b_mapper.UserMapper;
import com.lzy.chat.c_service.Exception.Exceptions;
import com.lzy.chat.c_service.Exception.ServiceException;
import com.lzy.chat.g_annotation.NeedToken;
import com.lzy.chat.g_annotation.PassToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        System.out.println("preHandle");
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有PassToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        if (method.isAnnotationPresent(NeedToken.class)) {
            NeedToken needToken = method.getAnnotation(NeedToken.class);
            //判断需要token
            if (needToken.required()) {
//                System.out.println(token);
                if (token == null) {
                    throw new ServiceException(Exceptions.TokenNotFoundException);
                }
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new ServiceException(Exceptions.TokenDecodeException, "token:" + token);
                }
                User user = userMapper.getUserById(Integer.parseInt(userId));
                if (user == null) {
                    throw new ServiceException(Exceptions.UserNotFoundException);
                }
                // 验证 token，因为我生成signature的时候加密的是用户salt，所以这里也需要用用户salt验证
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getSalt())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new ServiceException(Exceptions.TokenVerifyException);
                }
                request.getSession().setAttribute("currentUser", user);//储存user,以便controller使用
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
